package cn.yudao.ymcc.mq.listener;

import cn.yudao.ymcc.domain.CourseOrder;
import cn.yudao.ymcc.dto.Order2PayTranMesDto;
import cn.yudao.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(txProducerGroup ="txOrderPay")
public class Order2PayTranListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    // 执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        CourseOrder courseOrder = (CourseOrder) o; // 得到订单信息--执行本地事务
        // 执行本地事务
        try {
            boolean success = courseOrderService.saveOrderAndItem(courseOrder);
            if (success){
                return RocketMQLocalTransactionState.COMMIT;

            }else {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    // 检查本地事务状态
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            // 获取传入的信息
            byte[] payload = (byte[]) message.getPayload();
            String s = new String(payload, StandardCharsets.UTF_8);
            Order2PayTranMesDto order2PayTranMesDto = JSONObject.parseObject(s, Order2PayTranMesDto.class);
            CourseOrder courseOrder =  courseOrderService.selectByOrderNo(order2PayTranMesDto.getOrderNo());
            if (courseOrder != null){
                return RocketMQLocalTransactionState.COMMIT;
            }else {
                return RocketMQLocalTransactionState.ROLLBACK;
            }

        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
